package com.newdjk.newdoctor.ui;


import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.ajguan.library.EasyRefreshLayout;
import com.ajguan.library.LoadModel;
import com.google.gson.Gson;
import com.newdjk.newdoctor.BasActivity;
import com.newdjk.newdoctor.MyApplication;
import com.newdjk.newdoctor.R;
import com.newdjk.newdoctor.adapter.PatientListAdapter;
import com.newdjk.newdoctor.dialog.ShareDialog;
import com.newdjk.newdoctor.entity.AdBannerInfo;
import com.newdjk.newdoctor.entity.PatientListDataEntity;
import com.newdjk.newdoctor.entity.PatientListEntity;
import com.newdjk.newdoctor.entity.SendActivity;
import com.newdjk.newdoctor.entity.SendGoodEntity;
import com.newdjk.newdoctor.entity.SendGoodsEntity;
import com.newdjk.newdoctor.net.BaseComPleteObserver;
import com.newdjk.newdoctor.net.NetServices;
import com.newdjk.newdoctor.utils.Contants;
import com.newdjk.newdoctor.utils.SpUtils;
import com.newdjk.newdoctor.utils.ToastUtil;
import com.newdjk.newdoctor.view.ClearEditText;
import com.newdjk.okhttp.entity.BaseEntity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

import static java.util.regex.Pattern.compile;

/*
 *  @项目名：  Doctor
 *  @包名：    com.newdjk.doctor.ui.activity
 *  @文件名:   PatientListActivity
 *  @创建者:   huhai
 *  @创建时间:  2019/6/12 13:48
 *  @描述：
 */
public class PatientListActivity extends BasActivity {

    @BindView(R.id.et_patient_msg)
    ClearEditText etPatientMsg;
    @BindView(R.id.mSearchTv)
    TextView mSearchTv;
    @BindView(R.id.mSearchContainer)
    LinearLayout mSearchContainer;
    @BindView(R.id.recyleview)
    RecyclerView recyleview;
    @BindView(R.id.easylayout)
    EasyRefreshLayout easylayout;
    @BindView(R.id.iv_no)
    ImageView ivNo;
    @BindView(R.id.mNodataContainer)
    RelativeLayout mNodataContainer;
    private PatientListAdapter mPatientAdapter;
    private List<PatientListEntity.ReturnDataBean> mPaintList = new ArrayList<>();
    private List<PatientListEntity.ReturnDataBean> mPaintListSelect = new ArrayList<>();
    private String mPatientNameContent = "";
    private int mIndex = 1;
    private List<String> letterList = new ArrayList<>();
    private Gson mGson;
    private SendGoodsEntity mSendGoodsEntity;
    private ShareDialog mDialog;
    private int mType;
    private AdBannerInfo.DataBean mDataBean;
    private int pageindex = 1;

    @Override
    protected String setTitle() {
        return "患者列表";
    }

    @Override
    protected int initViewResId() {
        return R.layout.activity_apatientlist;
    }

    @Override
    public boolean IsShowBackIcon() {
        return true;
    }

    @Override
    protected void initView() {

        MyApplication.mActivities.add(this);
        mGson = new Gson();
        setRightText("发送(0)");
        String data = getIntent().getStringExtra("SendGoodsEntity");
        mDataBean = (AdBannerInfo.DataBean) getIntent().getSerializableExtra("bannerInfo");
//        mDataBean.setLinkContent("xxxxxxxxxxxxxxxxxx");
//        mDataBean.setShareTitle("活动分享");
//        mDataBean.setShareLink("www.baidu.com");
//        mDataBean.setShareCotent("娃哈哈娃哈哈哈哈哈哈哈哈哈哈哈傻大姐哈吉斯的哈建华大街回到家阿回到家安徽的");
        mType = getIntent().getIntExtra("type", 0);
        Log.d("PatientListActivity", "打印接受数据" + data);
        mSendGoodsEntity = mGson.fromJson(data, SendGoodsEntity.class);
        mPatientAdapter = new PatientListAdapter(this);
        recyleview.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        recyleview.setAdapter(mPatientAdapter);
    }

    @Override
    protected void initListener() {
        easylayout.addEasyEvent(new EasyRefreshLayout.EasyEvent() {
            @Override
            public void onLoadMore() {
                getPatientList();
            }

            @Override
            public void onRefreshing() {
                pageindex = 1;
                mPaintList.clear();
                letterList.clear();
                easylayout.setLoadMoreModel(LoadModel.COMMON_MODEL);
                getPatientList();
            }
        });

        etPatientMsg.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
//                if (TextUtils.isEmpty(s.toString())) {
//                    imClear.setVisibility(View.GONE);
//                } else {
//                    imClear.setVisibility(View.VISIBLE);
//                }
                pageindex = 1;
                mPaintList.clear();
                mPatientNameContent = etPatientMsg.getText().toString().trim();
                getPatientList();
            }
        });


        mPatientAdapter.setOnItemClickListener(new PatientListAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                // toast("点击了");

                //  showSharedialog(position);
                if (mPaintList.size() > 0) {
                    boolean isselect = mPaintList.get(position).isIselect();
                    if (isselect) {
                        mPaintList.get(position).setIselect(false);
                        //移除对应id的数据
                        if (mPaintListSelect.size() > 0) {
                            for (int i = mPaintListSelect.size() - 1; i >= 0; i--) {
                                if (mPaintList.get(position).getPatientId() == mPaintListSelect.get(i).getPatientId()) {
                                    mPaintListSelect.remove(i);
                                }
                            }
                        }
                    } else {
                        if (mPaintListSelect.size() >= 9) {
                            ToastUtil.setToast("最多只能选择9人");
                            ;
                            return;
                        }
                        mPaintList.get(position).setIselect(true);
                        mPaintListSelect.add(mPaintList.get(position));
                    }
                    setRightText("发送(" + mPaintListSelect.size() + ")");
                    mPatientAdapter.notifyItemChanged(position);
                }


            }

            @Override
            public void onItemchildClick(View view, int position) {
                //  toast("选中");
            }
        });

    }

    @Override
    protected void onRightTvClick(View v) {
        super.onRightTvClick(v);
        if (mPaintListSelect.size() == 0) {
            ToastUtil.setToast("最少选择一人进行分享");
            return;
        }
        showSharedialog(mPaintListSelect);
    }

    @Override
    protected void initData() {
        getPatientList();
    }


    public void getPatientList() {

        NetServices.Factory.getService().QueryDoctorPatientPage(
                MyApplication.LoginEntity.getUser().getDoctorId(),
                "-1",
                "1",
                "-1",
                "-1",
                mPatientNameContent,
                pageindex,
                10

        ).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseComPleteObserver<PatientListEntity>(PatientListActivity.this) {
                    @Override
                    protected void onSuccees(BaseEntity<PatientListEntity> t) throws Exception {

                        if (pageindex != 1) {
                            easylayout.loadMoreComplete();
                        } else {
                            easylayout.refreshComplete();
                        }
                        List<PatientListEntity.ReturnDataBean> returnlist = t.getData().getReturnData();
                        if (returnlist != null) {
                            if (returnlist.size() == 10) {  //还有数据
                                pageindex++;
                                mPaintList.addAll(returnlist);
                                mPatientAdapter.setDatalist(mPaintList);

                            } else if (returnlist.size() >= 0 && returnlist.size() < 10) { //加载完成
                                pageindex++;
                                mPaintList.addAll(returnlist);
                                mPatientAdapter.setDatalist(mPaintList);


                                easylayout.setLoadMoreModel(LoadModel.NONE);
                            }
                            //  reFreshNameLetter(returnlist);

                        }

                        if (mPaintList.size() <= 0) {
                            Log.i("MessageFragment", "lenError");
                            // mEasylayout.setVisibility(View.GONE);
                            recyleview.setVisibility(View.GONE);
                            mNodataContainer.setVisibility(View.VISIBLE);
                        } else {
                            //  mEasylayout.setVisibility(View.VISIBLE);
                            recyleview.setVisibility(View.VISIBLE);
                            mNodataContainer.setVisibility(View.GONE);
                        }


                    }

                    @Override
                    protected void onFailure(Throwable e, String erroressage, boolean isNetWorkError) throws Exception {
                        super.onFailure(e, erroressage, isNetWorkError);

                        easylayout.loadMoreFail();
                        if (mPaintList.size() <= 0) {
                            Log.i("MessageFragment", "lenError");
                            // mEasylayout.setVisibility(View.GONE);
                            recyleview.setVisibility(View.GONE);
                            mNodataContainer.setVisibility(View.VISIBLE);
                        } else {
                            //  mEasylayout.setVisibility(View.VISIBLE);
                            recyleview.setVisibility(View.VISIBLE);
                            mNodataContainer.setVisibility(View.GONE);
                        }

                    }
                });


    }


    //判断字符串是不是以数字开头
    public static boolean isStartWithNumber(String str) {
        Pattern pattern = compile("[0-9]*");
        Matcher isNum = pattern.matcher(str.charAt(0) + "");
        return isNum.matches();
    }

    private void showSharedialog(List<PatientListEntity.ReturnDataBean> list) {
        if (mDialog == null) {
            mDialog = new ShareDialog(PatientListActivity.this);
        }
        mDialog.show(list, new ShareDialog.DialogListener() {
            @Override
            public void cancel() {

            }

            @Override
            public void confirm() {
                if (mType == 0) {
                    SendGoodsRecommend(mPaintListSelect);

                } else {
                    SendWXMessageToPatient(mPaintListSelect);
                }
            }

            @Override
            public void remove(int patientid) {

                for (int i = 0; i < mPaintList.size(); i++) {
                    if (mPaintList.get(i).getPatientId() == patientid) {
                        mPaintList.get(i).setIselect(false);
                        mPatientAdapter.notifyItemChanged(i);
                    }
                }

                setRightText("发送(" + mPaintListSelect.size() + ")");
            }
        });
    }

    //分享活动
    private void SendWXMessageToPatient(List<PatientListEntity.ReturnDataBean> selectlist) {

        if (mDataBean == null) {
            ToastUtil.setToast("分享失败");
            return;
        }

        if (selectlist.size() == 0) {
            ToastUtil.setToast("最少选择一个病人");
            return;
        }
        if (TextUtils.isEmpty(mDataBean.getShareCotent())) {
            ToastUtil.setToast("分享内容为空，请重新登录并检查数据");
            return;
        }

        if (TextUtils.isEmpty(mDataBean.getShareLink())) {
            ToastUtil.setToast("分享连接为空，请重新登录并检查数据");
            return;
        }
        if (TextUtils.isEmpty(mDataBean.getShareLink())) {
            ToastUtil.setToast("分享标题为空，请重新登录并检查数据");
            return;
        }

        SendActivity sendActivity = new SendActivity();
        List<SendActivity.PatientsBean> list = new ArrayList<>();
        for (int i = 0; i < selectlist.size(); i++) {
            SendActivity.PatientsBean patientsBean = new SendActivity.PatientsBean();
            patientsBean.setAccountId(selectlist.get(i).getAccountId());
            patientsBean.setPatientName(selectlist.get(i).getPatientName());
            list.add(patientsBean);
        }
        sendActivity.setPatients(list);
        sendActivity.setContent(mDataBean.getShareCotent());
        sendActivity.setDrId(MyApplication.LoginEntity.getUser().getDoctorId());
        sendActivity.setShareLink(mDataBean.getShareLink().replace("{drid}", String.valueOf(SpUtils.getInt(Contants.Id, 0))));
        sendActivity.setTitle(mDataBean.getShareTitle());
        sendActivity.setTitle(mDataBean.getShareTitle());
        String json = mGson.toJson(sendActivity);
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
        NetServices.Factory.getService().SendWXMessageToPatient(
                body
        ).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseComPleteObserver(PatientListActivity.this) {
                    @Override
                    protected void onSuccees(BaseEntity t) throws Exception {
                        ToastUtil.setToast("群发消息成功");
                        finish();
                        return;

                    }

                });
    }


    //分享商品
    private void SendGoodsRecommend(List<PatientListEntity.ReturnDataBean> selectlist) {
        if (mSendGoodsEntity == null) {
            ToastUtil.setToast("分享内容为空");
            return;
        }
        if (selectlist.size() == 0) {
            ToastUtil.setToast("最少选择一个病人");
            return;
        }
        SendGoodEntity sendGoodEntity = new SendGoodEntity();
        List<Integer> list = new ArrayList<>();
        sendGoodEntity.setDataId(mSendGoodsEntity.getDataId());
        sendGoodEntity.setDataSource(mSendGoodsEntity.getDataSource());
        for (int i = 0; i < selectlist.size(); i++) {
            list.add(selectlist.get(i).getPatientId());
        }
        sendGoodEntity.setPatientIdList(list);
        String json = mGson.toJson(sendGoodEntity);


        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
        NetServices.Factory.getService().SendGoodsRecommend(
                body
        ).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseComPleteObserver(PatientListActivity.this) {
                    @Override
                    protected void onSuccees(BaseEntity t) throws Exception {
                        ToastUtil.setToast("分享成功");
                        finish();
                        return;

                    }

                    @Override
                    protected void onFailure(Throwable e, String erroressage, boolean isNetWorkError) throws Exception {
                        super.onFailure(e, erroressage, isNetWorkError);
                        ToastUtil.setToast("分享失败");
                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MyApplication.mActivities.remove(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
